package edu.cebanc.spring.biblioteca.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.cebanc.spring.biblioteca.bean.EjemplarBean;
import edu.cebanc.spring.biblioteca.bean.PrestamoBean;
import edu.cebanc.spring.biblioteca.service.IndexService;

@Controller
public class IndexController {
	
	@Autowired
	IndexService indexService;
	EjemplarBean ejemplar;
	
	@RequestMapping(value="/login")
	public String loginView(Model model){
		
		return "indexLogin";
	}
	
	@RequestMapping(value="/logout")
	public String logoutView(Model model){
		
		return "indexLogin";
	}
	
	@RequestMapping(value="/loginfailed")
	public String loginFailView(Model model){
		
		model.addAttribute("error", "true");
		
		return "indexLogin";
	}
	
	@RequestMapping(value="/index", method=RequestMethod.GET)
	public String getMainView(Model model){
		
		List<EjemplarBean> ejemplares = indexService.getEjemplaresDisp();
		
		List<String> errores = new ArrayList<String>();
		
		if(ejemplares == null){
			errores.add("Fallo al obtener Ejemplares");
		}
		
		model.addAttribute("errores", errores);
		model.addAttribute("ejemplares", ejemplares);
		
		return "indexMain";
	}
	
	@RequestMapping(value="reservaEjemplar/{id}", method=RequestMethod.GET)
	public String getReservaEjemplarView(@PathVariable String id, Model model){
		
		this.ejemplar = indexService.getEjemplar(id);
		model.addAttribute("prestamo", new PrestamoBean());
		
		return "ejemplarReservaForm";
	}
	
	@RequestMapping(value="dataReservaEjemplar", method=RequestMethod.POST)
	public String dataReservaEjemplar(PrestamoBean prestamo, BindingResult result, Model model){

		if(result.hasErrors()){
			model.addAttribute("prestamo", prestamo);
		}
		
		//indexService.reservarEjemplar(id_usuario, this.ejemplar.getId_ejemplar());
		return "redirect:/";
	}
}
